package com.sau.pixelcart.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sau.pixelcart.common.exception.BusinessException;
import com.sau.pixelcart.common.result.PageResult;
import com.sau.pixelcart.domain.dto.CategoryDTO;
import com.sau.pixelcart.domain.dto.CategoryPageDTO;
import com.sau.pixelcart.domain.entity.Category;
import com.sau.pixelcart.domain.entity.Product;
import com.sau.pixelcart.domain.entity.ProductInventory;
import com.sau.pixelcart.domain.vo.CategoryVO;
import com.sau.pixelcart.mapper.CategoryMapper;
import com.sau.pixelcart.mapper.ProductMapper;
import com.sau.pixelcart.service.ICategoryService;
import com.sau.pixelcart.service.IProductInventoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private IProductInventoryService productInventoryService;

    /**
     * 分类分页查询
     * @param categoryPageDTO
     * @return
     */
    @Override
    public PageResult<CategoryVO> queryPage(CategoryPageDTO categoryPageDTO) {
        //开始分页
        Page<Category> page = new Page<>(categoryPageDTO.getPage(), categoryPageDTO.getPageSize());

        //查询条件
        LambdaQueryWrapper<Category> categoryWrapper = new LambdaQueryWrapper<>();
        Page<Category> categoryPage = categoryMapper.selectPage(page, categoryWrapper);

        //查出所有上架的商品信息存入List中
        LambdaQueryWrapper<Product> productWrapper = new LambdaQueryWrapper<>();
        productWrapper.eq(Product::getStatus,"active");
        List<Product> productList = productMapper.selectList(productWrapper);

        //查出所有库存Map<productId,entity>
        Map<String, Integer> productInventoryStockMap = productInventoryService.list().stream().collect(Collectors.toMap(ProductInventory::getProductId,ProductInventory::getStock));

        //遍历分类列表
        List<Category> categoryList = categoryPage.getRecords();
        //每个分类下的商品
        Map<String, List<Product>> categoryProductMap = categoryList.stream()
                .collect(Collectors.toMap(
                        Category::getId,
                        category -> productList.stream()
                                .filter(product -> product.getCategoryId().equals(category.getId()))
                                .collect(Collectors.toList()),
                        (existing, replacement) -> existing
                ));

        //转成VO对象
        List<CategoryVO> categoryVOList = categoryList.stream().map(category -> {
            //查询商品表中该分类的总数量
            CategoryVO categoryVO = new CategoryVO();
            BeanUtils.copyProperties(category, categoryVO);
            List<Product> productList1 = categoryProductMap.get(category.getId());
            Integer totalStock = 0;
            Integer count = 0;
            for (Product product : productList1) {
                Integer stock = productInventoryStockMap.get(product.getId());
                totalStock += stock;
                count ++;
            }
            categoryVO.setTotal(Long.valueOf(totalStock));
            categoryVO.setProductNum(Long.valueOf(count));
            return categoryVO;
        }).collect(Collectors.toList());

        //封装返回值
        PageResult<CategoryVO> pageResult = new PageResult<>();
        pageResult.setTotal(categoryPage.getTotal());
        pageResult.setRecords(categoryVOList);
        return pageResult;
    }

    /**
     * 保存分类
     * @param categoryDTO
     */
    @Override
    public void saveOrUpdate(CategoryDTO categoryDTO) {
        //判断信息是否重复
        if(categoryDTO.getId() == null || categoryDTO.getId().isEmpty()){
            //没有分类信息，进行添加操作
            Category category = new Category();
            BeanUtils.copyProperties(categoryDTO, category);
            category.setCreateTime(LocalDateTime.now());
            category.setUpdateTime(LocalDateTime.now());
            categoryMapper.insert(category);
        }else{
            //有分类信息，进行修改操作
            Category category = new Category();
            BeanUtils.copyProperties(categoryDTO, category);
            category.setUpdateTime(LocalDateTime.now());
            categoryMapper.updateById(category);
        }


    }

    /**
     * 删除分类
     * @param id
     */
    @Override
    public void deleteById(String id) {
        //判断当前分类下是否有商品
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Product::getCategoryId,id);
        List<Product> productList = productMapper.selectList(wrapper);
        if(!productList.isEmpty()){
            //当前分类下有商品
            throw new BusinessException("当前分类下有商品，无法删除");
        }
        categoryMapper.deleteById(id);
    }

    @Override
    public List<CategoryVO> getAllCategory() {
        List<Category> categoryList = lambdaQuery().list();
        List<CategoryVO> categoryVOList = new ArrayList<>();
        categoryList.forEach(category -> {
            CategoryVO categoryVO = new CategoryVO();
            BeanUtils.copyProperties(category, categoryVO);
            categoryVOList.add(categoryVO);
        });
        return categoryVOList;
    }

    /**
     * 计算分类下的库存总数
     * @param total
     * @param number
     * @return
     */
    private Long sumTotalProduct(Long total, Integer number) {

        total += number;
        return total;
    }
}
